import hashlib
from django.utils.deprecation import MiddlewareMixin
from django.http import JsonResponse, HttpResponse, Http404

from log.tools import record_log
from .settings import NOTOKENPATH
from django.core.cache import cache
from .log import output_log
from django.db.utils import *
from .err import *

# token检查
class TokenCheckMiddleware(MiddlewareMixin):

    # 校验token
    def is_valid_token(self, token):
        userid = cache.get(token,None)
        if userid is None:
            return None
        return userid
        
    def process_request(self, request):
        token = request.META.get("HTTP_AUTHORIZATION")
        
        # 白名单路径不检查token
        if request.path in NOTOKENPATH:
            return None  
        
        # token不存在直接报错
        if token is None:
            return JsonResponse({"status": 401, "msg": "Token不能为空!"})
        
        # 验证 token
        userid = self.is_valid_token(token)
        if userid is None:
            return JsonResponse({"status": 401, "msg": "Token不合法!"})
        else:
            # 保存 userid到 request 上下文
            setattr(request,'userid',userid)
            return None

# 解决跨域
# class CorsMiddleware(MiddlewareMixin):
    
#     def process_request(self,request):
#         if  request.method == 'OPTIONS':
#             response = HttpResponse()
#             response["Access-Control-Allow-Origin"] = "*"
#             response["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
#             response["Access-Control-Allow-Headers"] = "Content-Type, Authorization, X-Custom-Header"
#             return response
    
#     def process_response(self, request, response):
#         response["Access-Control-Allow-Origin"] = "*"
#         response["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
#         response["Access-Control-Allow-Headers"] = "Content-Type, Authorization, X-Custom-Header"      
#         return response

# 处理错误



# 错误处理
class ExceptionMiddleware(MiddlewareMixin):

    def process_exception(self, request, exception):
        output_log(f"发生错误！request:{request.path},err:{exception}", level="error")
        # 写入数据库日志记录
        if isinstance(exception, SaveLogErr):
            pass
        else:
            record_log(module="错误拦截器",cls=3,msg=exception.__str__())
        #  判断错误种类进行返回信息修改
        if isinstance(exception, IntegrityError):
            if exception.__str__() == "UNIQUE constraint failed: user.username":
                return JsonResponse({"status": 400,"msg": "账户名已使用!"})
            return JsonResponse({"status": 400,"msg": "服务器发生错误，请联系管理员!","err": f"err:{exception}"})
        elif isinstance(exception, ValueSaveError):
            return JsonResponse({"status": 400,"msg": "服务器发生错误，请联系管理员!","err": f"数据保存失败！err:{exception}"})
        elif isinstance(exception, MethodNotAllowedErr):
            return JsonResponse({"status": 400, "msg": "服务器发生错误，请联系管理员!","err": f"请求失败！err:{exception}"})
        elif isinstance(exception, PermissionDeniedErr):
            return JsonResponse(
                {"status": 400, "msg": "用户权限不足无法访问!", "err": f"请求失败！err:{exception}"})
        elif isinstance(exception, SaveLogErr):
            return JsonResponse(
                {"status": 400, "msg": "服务器发生错误，请联系管理员!", "err": f"请求失败！err:{exception}"})


        return JsonResponse({"status": 400,"msg": "服务器发生错误，请联系管理员!"})

